package index;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import shopping.Dish;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;

@WebServlet("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
        maxFileSize = 1024 * 1024 * 10,      // 10MB
        maxRequestSize = 1024 * 1024 * 50)   // 50MB
public class FileUploadServlet extends HttpServlet {

    // 文件存储目录
    private static final String UPLOAD_DIR = "uploads";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 获取上传目录绝对路径
        String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIR;
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) uploadDir.mkdir();

        // 菜品信息
        String dishName = request.getParameter("dishName");
        String priceStr = request.getParameter("price");
        Part filePart = request.getPart("file");

        try {
            // 文件处理
            String fileName = UUID.randomUUID() + "_" + getFileName(filePart);
            String filePath = uploadPath + File.separator + fileName;
            filePart.write(filePath);

            // 保存到数据库
            Dish dish = new Dish();
            dish.setName(dishName);
            dish.setPrice(Double.parseDouble(priceStr));
            dish.setImage(UPLOAD_DIR + "/" + fileName); // 保存相对路径

            if (insertDish(dish)) {
                response.sendRedirect("WelcomeServlet?status=upload_success");
            } else {
                response.sendRedirect("error.jsp?msg=Upload failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("error.jsp?msg=" + e.getMessage());
        }
    }

    private boolean insertDish(Dish dish) {
        String sql = "INSERT INTO dishes(name, price, image) VALUES(?, ?, ?)";
        try (Connection conn = JdbcUtils.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, dish.getName());
            ps.setDouble(2, dish.getPrice());
            ps.setString(3, dish.getImage());
            return ps.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取上传文件名
    private String getFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        String[] items = contentDisp.split(";");
        for (String s : items) {
            if (s.trim().startsWith("filename")) {
                return s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        return "";
    }
}
